import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

    if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/access-control/index' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      console.log('hasRoles',hasRoles,store.getters.roles)
      if (hasRoles) {
        // 如果有角色但没有用户名，恢复用户信息
        if (!store.getters.name) {
          await store.dispatch('user/getInfo')
        }
        next()
      } else {
        try {
          // 恢复用户信息（包括用户名）
          await store.dispatch('user/getInfo')
          
          // 不调用后端接口，直接将所有登录用户视为admin角色
          const roles = ['admin']
          
          // 存储角色信息到store
          await store.commit('user/SET_ROLES', roles)

          // 根据角色生成可访问路由
          console.log('生成路由前的角色:', roles)
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          console.log('生成的动态路由:', accessRoutes)
          
          // 动态添加可访问路由
          router.addRoutes(accessRoutes)
          
          // 打印添加路由后的permission_routes
          console.log('当前所有路由:', store.getters.permission_routes)

          // hack方法确保addRoutes已完成
          next({ ...to, replace: true })
        } catch (error) {
          // 如果出错，删除token并跳转到登录页重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || '权限验证失败')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
